package com.adu.exceltest.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;

import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.adu.exceltest.domain.ExcelEntity;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RestController
public class TestController {
    @Value("${file.path}")
    String dirPath;

    /**
     * 导出excel
     * @return
     * @throws IOException
     */
    @GetMapping("/exportExcel")
    public String exportExcel() throws IOException {
        List<ExcelEntity> list=new ArrayList();
        // 造20条数据
        for(int i=0;i<20;i++){
            ExcelEntity entity=new ExcelEntity();
            entity.setName("菜鸟阿都"+i);
            entity.setAddress("宝鸡市");
            // 随机产生数字0或1,根据实体类ExcelEntity中的配置,0会转换成'男',1转换为'女'
            Random random=new Random();
            int num=random.nextInt(2);
            entity.setSex(num);
            list.add(entity);
        }
        // 设置导出参数,excel中的title设置为空，sheet页的名字为sheet1
        ExportParams params=new ExportParams(null,"sheet1");
        // 判断excel存放目录是否存在，不存在时创建,dirPath值是从配置文件中通过@Value注解读取
        File path=new File(dirPath);
        if(!path.exists()){
            path.mkdirs();
        }
        // excel文件名称
        String fileName="测试.xls";
        Workbook workbook = ExcelExportUtil.exportExcel(params,ExcelEntity.class,list);
        // 通过文件输出流将excel写到文件中
        FileOutputStream fos = new FileOutputStream(dirPath+fileName);
        workbook.write(fos);
        // 关闭文件输出流
        fos.close();
        return "excel导出成功";
    }

    /**
     * 导入excel
     * @return
     * @throws IOException
     */
    @GetMapping("/importExcel")
    public List<ExcelEntity> importExcel() throws IOException {
        // 设置导入参数
        ImportParams params=new ImportParams();
        List<ExcelEntity> list = ExcelImportUtil.importExcel(
                new File(dirPath+"测试.xls"),
                ExcelEntity.class, params);
        return list;
    }
}
